package org.doc.noliferadio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

public class PropertiesManager {

    private static File propertiesLocation = new File(System.getenv("APPDATA") + File.separator + "OverlaySettings");
    private static Properties properties = new Properties();

    public static void init() {
        if (checkForProps()) {
            loadProperties();
        }
    }

    public static void saveProperties(Properties props) {
        properties = props;
    }

    public static void saveProperty(String property, String value) {
        properties.setProperty(property, value);
    }

    public static String getProperty(String property) {
        return properties.getProperty(property) != null ? properties.getProperty(property) : null;
    }

    private static boolean checkForProps() {
        System.out.println("Checking for properties file: " + propertiesLocation.getPath());
        if (propertiesLocation.exists() && propertiesLocation.isFile()) {
            return true;
        } else {
            try {
                return propertiesLocation.createNewFile();
            } catch (IOException ex) {
                Logger.getLogger(PropertiesManager.class.getName()).log(Level.SEVERE, null, ex);
            }
            return false;
        }
    }

    private static void loadProperties() {
        try {
            properties.loadFromXML(new FileInputStream(new File(propertiesLocation + ".xml")));
        } catch (Exception ex) {
            Logger.getLogger(PropertiesManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void save() {
        try {
            properties.storeToXML(new FileOutputStream(new File(propertiesLocation + ".xml")), null);
        } catch (Exception ex) {
            Logger.getLogger(PropertiesManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
